package com.jxs.android.cmcc;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.xmlpull.v1.XmlPullParserException;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.jxs.android.cmcc.boot.SelfApplication;
import com.jxs.android.cmcc.data.KipInfo;
import com.jxs.android.cmcc.data.MenuInfo;
import com.jxs.android.cmcc.db.KipConfigHolder;
import com.jxs.android.cmcc.db.KipHolder;
import com.jxs.android.cmcc.db.MenuHolder;
import com.jxs.android.soap.BuWebService;
import com.jxs.android.soap.IWebService;
import com.jxs.android.util.StartHelper;
import com.jxs.android.util.StringUtils;
import com.jxs.android.weiget.MenuPageView;
import com.jxs.android.weiget.PagedAdapter;
import com.jxs.android.weiget.PagedView;
import com.jxs.android.weiget.PagedView.OnPagedViewChangeListener;
import com.jxs.android.weiget.PopMsg;
import com.jxs.android.weiget.WheelDateDialog;

@SuppressLint("HandlerLeak")
public class Laucher extends AbstractListActivity {
	private final int REQ_KIP_GRID_CODE = 0xa789;
	private final int REQ_HITCH_TIME = 0xb789;
	private List<KipInfo> lKipInfos = new ArrayList<KipInfo>();
	@SuppressLint("UseSparseArrays")
	private Map<Integer, ArrayList<MenuInfo>> menuInfos = new HashMap<Integer, ArrayList<MenuInfo>>();

	private KipAdapter kipAdapter;
	private MenuAdapter menuAdapter;
	private PagedView kipPagedView, menuPagedView;
	private Context context;
	private ImageView kip_left, kip_right;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		context = this;
		initTopBar(savedInstanceState, R.layout.bu_main);
		kipPagedView = (PagedView) findViewById(R.id.kip_paged_view);
		menuPagedView = (PagedView) findViewById(R.id.menu_paged_view);
		kip_left = (ImageView) findViewById(R.id.kip_left);
		kip_right = (ImageView) findViewById(R.id.kip_right);

		if (StringUtils.isEmpety(SelfApplication.getDataReadModel()) || "1".equals(SelfApplication.getDataReadModel())) {
			refreshKipValus(KipConfigHolder.getDefualValue());
		} else {
			lKipInfos = KipHolder.getKipInfos(KipConfigHolder.getDefualValue());
			if (lKipInfos.size() == 0) {
				refreshKipValus(KipConfigHolder.getDefualValue());
			}
		}

		kipAdapter = new KipAdapter(lKipInfos);
		kipPagedView.setOnPageChangeListener(kipChangedListener);
		kipAdapter.setKipInfos(lKipInfos);
		kipPagedView.setAdapter(kipAdapter);
		kipAdapter.notifyDataSetChanged();

		menuInfos = MenuHolder.getMainMenuinfos();
		menuAdapter = new MenuAdapter();
		menuPagedView.setOnPageChangeListener(menuChangedListener);
		menuPagedView.setAdapter(menuAdapter);

		if (lKipInfos.size() == 1) {
			kip_left.setVisibility(View.GONE);
			kip_right.setVisibility(View.GONE);
		} else {
			kip_right.setVisibility(View.VISIBLE);
		}

		setKipActivePage(kipPagedView.getCurrentPage());
	}

	private void refreshKipValus(String statDate) {
		getWebServiceData(SelfApplication.getUserInfo().getTicket(), statDate, Which.STAT_DATE, true, new AbstractListActivity.DataInitListeren() {

			@Override
			public void initData(ProgressDialog progressDialog, boolean isShow) {
				progressDialog.dismiss();
			}
		});
	}

	private class KipAdapter extends PagedAdapter {

		private LayoutInflater inflater;
		private List<KipInfo> kipInfos = new ArrayList<KipInfo>();

		public KipAdapter(List<KipInfo> kipInfos) {
			inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			this.kipInfos = kipInfos;
		}

		public void setKipInfos(List<KipInfo> kipInfos) {
			this.kipInfos = kipInfos;
		}

		@Override
		public int getCount() {
			return kipInfos.size();
		}

		@Override
		public Object getItem(int position) {
			return kipInfos.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		public View getView(final int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder;
			if (convertView == null) {
				viewHolder = new ViewHolder();
				convertView = inflater.inflate(R.layout.kip_page_item, null);

				viewHolder.kip_time = (TextView) convertView.findViewById(R.id.kip_time);
				viewHolder.kip_name = (TextView) convertView.findViewById(R.id.kip_name);
				viewHolder.kip_name_1 = (TextView) convertView.findViewById(R.id.kip_name_1);
				viewHolder.kip_name_2 = (TextView) convertView.findViewById(R.id.kip_name_2);
				viewHolder.kip_name_3 = (TextView) convertView.findViewById(R.id.kip_name_3);

				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			KipInfo info = null;
			try {
				if (position >= kipInfos.size()) {
					info = kipInfos.get(position - 1);
				} else {
					info = kipInfos.get(position);
				}
			} catch (IndexOutOfBoundsException e) {
				info = new KipInfo();
			}
			viewHolder.kip_time.setText(info.getStat_date() + " " + info.getWeek_name());
			viewHolder.kip_name.setText(info.getKpi_name() + "");
			viewHolder.kip_name_1.setText(replate(info.getKpi_value_1()));
			if (!"-1".equals(info.getKpi_id())) {
				viewHolder.kip_name_2.setText(info.getKpi_name_2() + ":" + replate(info.getKpi_value_2()));
				viewHolder.kip_name_3.setText(info.getKpi_name_3() + ":" + replate(info.getKpi_value_3()));
			} else {
				viewHolder.kip_name_2.setText("");
				viewHolder.kip_name_3.setText("");
			}

			viewHolder.kip_time.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					showDateTime(REQ_HITCH_TIME);
				}
			});
			convertView.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View paramView) {
					Intent intent = new Intent(context, KipSelectGrid.class);
					startActivityForResult(intent, REQ_KIP_GRID_CODE);
				}
			});
			return convertView;
		}

		private String replate(String msg) {
			if (StringUtils.isEmpety(msg)) {
				return "无";
			}
			return msg;
		}

		private void showDateTime(int requestCode) {
			WheelDateDialog dateTimeDialog = new WheelDateDialog(context, requestCode, KipConfigHolder.getDefualValue());
			dateTimeDialog.setDateChangeListener(new WheelDateDialog.DateChangeListener() {
				@Override
				public void onKeySave(int requestCode, String dateTimeValue) {
					if (REQ_HITCH_TIME == requestCode) {
						refreshKipValus(dateTimeValue);
					}
				}
			});
			dateTimeDialog.show();
		}

		class ViewHolder {
			TextView kip_time;
			TextView kip_name;
			TextView kip_name_1;
			TextView kip_name_2;
			TextView kip_name_3;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQ_KIP_GRID_CODE && resultCode == RESULT_OK) {
			refreshKipValus(KipConfigHolder.getDefualValue());
		}
	}

	@SuppressLint({ "HandlerLeak", "HandlerLeak" })
	private Handler kipArrowHandler = new Handler() {

		@SuppressLint("HandlerLeak")
		@Override
		public void handleMessage(Message msg) {
			int position = msg.what;
			if (position == 0) {
				kip_left.setVisibility(View.VISIBLE);
				if (lKipInfos.size() == 1) {
					kip_left.setVisibility(View.GONE);
				}
				kip_left.setVisibility(View.GONE);
			} else if (position == lKipInfos.size() - 1) {
				kip_left.setVisibility(View.VISIBLE);
				kip_right.setVisibility(View.GONE);
			} else {
				kip_right.setVisibility(View.VISIBLE);
				kip_left.setVisibility(View.VISIBLE);
			}
		}

	};

	private class MenuAdapter extends PagedAdapter {

		private LayoutInflater inflater;

		public MenuAdapter() {
			inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			return menuInfos.size();
		}

		@Override
		public Object getItem(int position) {
			return menuInfos.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		public View getView(final int position, View convertView, ViewGroup parent) {
			MenuPageView menuPageView = (MenuPageView) inflater.inflate(R.layout.menu_page_gride_view, null);
			menuPageView.setNumColumns(4);
			menuPageView.setMenuInfos(menuInfos.get(position));
			menuPageView.setItemClickListern(new MenuPageView.ItemClickListern() {

				@Override
				public void callBack(MenuInfo menuInfo) {
					if ("notice".equals(menuInfo.getMenu_id())) {
						StartHelper.startActivity(NoticeList.class);
					} else if ("help".equals(menuInfo.getMenu_id())) {
						StartHelper.startActivity(FeatureGuide.class);
					} else {
						Intent intent = new Intent(context, SubMain.class);
						Bundle bundle = new Bundle();
						bundle.putSerializable("menuInfo", menuInfo);
						intent.putExtras(bundle);
						startActivity(intent);
					}
				}
			});
			return menuPageView;
		}

	}

	private OnPagedViewChangeListener kipChangedListener = new OnPagedViewChangeListener() {

		@Override
		public void onStopTracking(PagedView pagedView) {
		}

		@Override
		public void onStartTracking(PagedView pagedView) {
		}

		@Override
		public void onPageChanged(PagedView pagedView, int previousPage, int newPage) {
			setKipActivePage(newPage);
		}
	};
	private OnPagedViewChangeListener menuChangedListener = new OnPagedViewChangeListener() {

		@Override
		public void onStopTracking(PagedView pagedView) {
		}

		@Override
		public void onStartTracking(PagedView pagedView) {
		}

		@Override
		public void onPageChanged(PagedView pagedView, int previousPage, int newPage) {
		}
	};

	private void setKipActivePage(int page) {
		kipArrowHandler.sendEmptyMessage(page);
	}

	@Override
	public String getMethod() {
		return "getKpiValueList";
	}

	private static final int UPDATE_LIST_UI = 0x403;
	private static final int TO_LOGIN = 0x444;
	private static final int ERROR_MSG = 0x405;
	Handler handler = new Handler() {

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == UPDATE_LIST_UI) {
				lKipInfos.clear();
				lKipInfos.addAll((List<KipInfo>) msg.obj);

				if (lKipInfos.size() == 0) {
					KipInfo setKipInfo = new KipInfo();
					setKipInfo.setKpi_id("-1");
					setKipInfo.setKpi_value_1("请配置指标");
					lKipInfos.add(setKipInfo);
				}
				if (lKipInfos.size() == 1) {
					kip_right.setVisibility(View.GONE);
					kip_left.setVisibility(View.GONE);
				} else {
					kip_right.setVisibility(View.VISIBLE);
				}
				kipAdapter.setKipInfos(lKipInfos);
				kipAdapter.notifyDataSetChanged();
			} else if (msg.what == ERROR_MSG) {
				PopMsg.show((String) msg.obj);
			} else if (msg.what == TO_LOGIN) {
				PopMsg.show((String) msg.obj);
				StartHelper.startActivity(Login.class);
				finish();
			}
		}

	};

	@Override
	protected void paser(String param, SoapObject soapObject) {
		if (null != soapObject) {
			String stauts = soapObject.getPropertySafelyAsString("status");
			SoapObject msgObjec = (SoapObject) soapObject.getProperty("msg");
			String message = msgObjec.getPropertySafelyAsString("message");
			if ("-2".equals(stauts)) {
				Message msg = new Message();
				msg.what = ERROR_MSG;
				msg.obj = message;
				handler.sendMessage(msg);
			} else if ("-1".equals(stauts)) {
				Message msg = new Message();
				msg.what = TO_LOGIN;
				msg.obj = message;
				handler.sendMessage(msg);
			} else if ("0".equals(stauts)) {
				SoapObject retMsgObject = (SoapObject) soapObject.getProperty("retMsg");
				List<KipInfo> kipInfoListInfos = new ArrayList<KipInfo>();
				if (null != retMsgObject) {
					for (int i = 0; i < retMsgObject.getPropertyCount(); i++) {
						SoapObject taskBeanObject = (SoapObject) retMsgObject.getProperty(i);

						KipInfo kipInfo = new KipInfo();
						kipInfo.setKpi_id(taskBeanObject.getPropertySafelyAsString("kpi_id"));
						kipInfo.setKpi_name(taskBeanObject.getPropertySafelyAsString("kpi_name"));
						kipInfo.setKpi_name_1(taskBeanObject.getPropertySafelyAsString("kpi_name_1"));
						kipInfo.setKpi_name_2(taskBeanObject.getPropertySafelyAsString("kpi_name_2"));
						kipInfo.setKpi_name_3(taskBeanObject.getPropertySafelyAsString("kpi_name_3"));
						kipInfo.setKpi_value_1(taskBeanObject.getPropertySafelyAsString("kpi_value_1"));
						kipInfo.setKpi_value_2(taskBeanObject.getPropertySafelyAsString("kpi_value_2"));
						kipInfo.setKpi_value_3(taskBeanObject.getPropertySafelyAsString("kpi_value_3"));
						kipInfo.setStat_date(taskBeanObject.getPropertySafelyAsString("stat_date"));
						kipInfo.setWeek_name(taskBeanObject.getPropertySafelyAsString("week_name"));

						KipHolder.saveOrUpdate(StringUtils.getStringDigits(kipInfo.getStat_date()), kipInfo);
						kipInfoListInfos.add(kipInfo);
					}
				}
				Message msg = new Message();
				msg.what = UPDATE_LIST_UI;
				msg.obj = kipInfoListInfos;
				handler.sendMessage(msg);
			}
		}
	}

	private final int SHARE_ID = 0xabc01;
	private final int EXIT_ID = 0xabc02;
	private MenuItem.OnMenuItemClickListener menuItemClickListener = new MenuItem.OnMenuItemClickListener() {

		@Override
		public boolean onMenuItemClick(MenuItem item) {
			if (item.getItemId() == SHARE_ID) {
				StartHelper.startActivity(ShareApp.class);
			} else if (item.getItemId() == EXIT_ID) {
				processMenuClose(context);
			}
			return false;
		}
	};

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.clear();
		MenuItem exitItem = menu.add(0, EXIT_ID, 402, "退出");// 可以通过点击这个菜单项来改变tv1的值这样(变成M)就可以测试了
		exitItem.setIcon(R.drawable.menu_exit);
		exitItem.setOnMenuItemClickListener(menuItemClickListener);

		MenuItem shareItem = menu.add(0, SHARE_ID, 401, "推荐");
		shareItem.setIcon(R.drawable.ic_menu_share);
		shareItem.setOnMenuItemClickListener(menuItemClickListener);

		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			processMenuClose(context);
		}
		return false;
	}

	/**
	 * @Des 处理关闭
	 * @param context
	 */
	private void processMenuClose(Context context) {
		AlertDialog.Builder builder = new Builder(context);
		builder.setMessage("确认退出吗？");
		builder.setTitle("提示");
		builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				logout();
				Laucher.this.finish();
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.create().show();
	}

	private void logout() {
		new Thread() {
			public void run() {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	protected void realyLogout(String ticket) {
		String wsdl_url = SelfApplication.WSDL_URL;// wsdl
		String namespace = SelfApplication.WSDL_NAME_SPACE;// namespace
		String methodName = "logout";// 要调用的方法名称
		SoapObject request = new SoapObject(namespace, methodName);
		request.addProperty("ticket", ticket);

		BuWebService webService = new BuWebService(wsdl_url, request);
		webService.setDoNet(false);
		webService.requestWSDL(new IWebService() {
			@Override
			public void logic(SoapSerializationEnvelope envelope) throws IOException, XmlPullParserException {
				Log.i("LOG_OUT", envelope.toString());
			}
		});
	}

}
